<?php
/**
 * 养殖
 * 
 * Created	: 2010-10-22
 * Modified : 2010-10-22
 * @author  : 陈立强
 */
class Raise
{

	public static $info = null;
	public static $cfg  = null;
	public static $cfgName = 'build/raise';

	public static $proficiencyTypeIdList = array(
		1 => 3,
		2 => 4,
		3 => 5,
	);
	
	/**
	 * 初始化玩家的养殖建筑信息
	 * @param int $uid
	 */
	public static function init ($uid)
	{
		global $DB, $L, $G;
		if (!$uid) {
			return false;
		}
		
		$data = array();
		$lvl = self::getLvl($uid);
		
		$raiseCfg = C('build/raise');
		$spaceNum = $raiseCfg[$lvl]['space_num'];

		$DB->beginTransaction();
		for ($pos=1; $pos<=$spaceNum; $pos++) {
			// 更新数据
			$data = array(
				'uid'       	=> $uid,
				'pos'       	=> $pos,
				'status'		=> 0,
				'now_animal'	=> 0,
				'now_product'	=> 0,
				'raise_time'	=> 0,
				'growend_time'	=> 0,
				'end_sc_time'	=> 0,
				'num'			=> '',
				'food_val'		=> $G['default_food_val'],
				'mood_val'		=> $G['default_mood_val'],
			);
			$ret = $DB->insert('raise', $data);
			if (!$ret) {
				$DB->rollBack();
				break;
			}
		}
		if ($ret) {
			$DB->commit();
		} else {
			$DB->rollBack();
		}
		return $ret;
	}
	
	/**
	 * 获取一个栏位信息
	 * @param int $uid 用户ID
	 * @param int $pos 栏位
	 * @param int $updateRipeInfo 更新栏位信息
	 */
	public static function getSpaceInfo($uid, $pos, $updateRipeInfo=1)
	{
		global $DB, $L;
		$sql    = 'SELECT * FROM raise WHERE uid=:uid and pos=:pos';
		$params = array('uid'=>$uid, 'pos'=>$pos);
		$info   = self::$info = $DB->getValue($sql, $params);
		if (false === $info) {
			return array(
				'val' => false,
				'msg' => $L['Failure_Read']
			);
		}
		// 不是自己的养殖空位信息不能获取
		if ($info['uid'] != $uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		if ($updateRipeInfo) {
			$info = self::handleSpaceInfo($info);
		}
		return $info;
	}
	
	/**
	 * 处理养殖的空位信息
	 * @param array $info
	 */
	private static function handleSpaceInfo($info)
	{
		global $DB, $L, $G;
		
		$animalList	= C('item/animal');
		// 无动物信息,不处理,直接返回
		if (!$info['now_animal']) {
			$info['title'] = '';
			$info['skill_type'] = '';
			return $info;
		}
		
		// 当前时间
		$now = $_SERVER['REQUEST_TIME'];
		
		$animalList	= C('item/animal');
		$animalCfg	= $animalList[$info['now_animal']];
		// 上次扣除饱食度的时间
		if ($info['last_reduce_food_val_time']) {
			$_time = $info['last_reduce_food_val_time'];
		} else {
			$info['last_reduce_food_val_time'] = $info['raise_time'];
			$_time = $info['last_reduce_food_val_time'];
		}
		
		// 判断是否成长结束
		if ($info['growend_time'] > 0 && $info['growend_time'] <= $now) {
			$endScNeedTime	= $animalCfg['ripe_need_time'];
			$info['end_sc_time']	= $endScNeedTime + $info['growend_time'];
			$info['status']			= 2;
			$info['growend_time']	= 0;
			$_time = $info['growend_time'];
		}
		
	
		// 计算上次生产结束时间到现在可以生产的次数,
		if (!$info['end_sc_time']) {
			$scNum = 0;
		} else if ($now == $info['end_sc_time']) {
			$scNum = 1;
		} else if ($now > $info['end_sc_time'] && $info['food_val']) {
			$needSeconds = $animalCfg['food_val_reduce_need_seconds'];
			$intervalTime = $info['end_sc_time'] - $info['last_reduce_food_val_time'];
			$needFoodVal = floor($intervalTime/$needSeconds);
			// 剩余饱食度无法坚持到下次生产结束,可生产次数还是为0
			if ($needFoodVal > $info['food_val']) {
				$scNum = 0;
			} else {
				// 上次生产结束后下一次生产结束时间,所以用ceil
				$scNum = ceil(($now - $info['end_sc_time'])/$animalCfg['ripe_need_time']);
			}
		} else {
			$scNum = 0;
		}
		$scNum = min($scNum, $info['harvest_times']);
	
		// 当前产品数据解析成数组
		if (is_string($info['num']) && $info['num']) {
			$outputItems = json_decode($info['num'], true);
		} else {
			$outputItems = array();
		}
		//-- 生成成熟的动物产品及数量
		$baseOutput = $animalCfg['base_output'];
	
		if ($scNum > 0) {
			// 循环处理每次生产的情况
			for ($i=0; $i<$scNum; $i++) {
				// 当前生产结束之前是否饱食度为0
				$needSeconds = $animalCfg['food_val_reduce_need_seconds'];
				$intervalTime = $info['end_sc_time'] - $info['last_reduce_food_val_time'];
				$needFoodVal = floor($intervalTime/$needSeconds);
				$remainFoodVal = $info['food_val'] - $needFoodVal;
				// 当前次生产完成之前饱食度已用完,则不再进行本次生产
				// 生产状态退回上一次状态
				if ($remainFoodVal < 0) {
					$scNum = $i;
					$info['end_sc_time'] -= $animalCfg['ripe_need_time'];
					$remainFoodVal += $needFoodVal;
					break;
				}
				// 下次结束生产的时间
				$info['end_sc_time'] += $animalCfg['ripe_need_time'];
				
				$rnd = round(rand(60, 100)/100, 2);
				$moodAddition = $info['mood_val'] * $G['raise_mood_val_param'];
				$output     = $baseOutput * $rnd + $moodAddition;
				// 根据最终产量数量取配置结果
				$outputCfg = C('output/animal_output');
				$num = getRangeKeyValue($output, $outputCfg);
				foreach($num as $k=>$v) {
					if (isset($outputItems[$k])) {
						$outputItems[$k] += $v;
					} else {
						$outputItems[$k] = $v;
					}
				}
			}
			// 收获次数减少
			$info['harvest_times'] -= $scNum;
			$info['num'] = json_encode($outputItems);
			// 计算最后一次需要扣除饱食度的数量和时间
			$needSeconds = $animalCfg['food_val_reduce_need_seconds'];
			if ($info['end_sc_time'] > $now) {
				$intervalTime = $now - $info['last_reduce_food_val_time'];
			}
			// 最后一次生产时间后没有可生产次数,则饱食度不再减少
			else if ($info['harvest_times'] == 0) {
				$intervalTime = $info['end_sc_time'] - $info['last_reduce_food_val_time'];
			}
			// 还有可生产次数,最后一次生产时间后不到一个周期,饱食度会减少为0
			// 生产周期持续到下一次
			else {
				$intervalTime = $now - $info['last_reduce_food_val_time'];
				$info['end_sc_time'] += $animalCfg['ripe_need_time'];
			}
			$needFoodVal = floor($intervalTime/$needSeconds);
			
			// 保存的经验(玩家没及时收获,经验每次结束生产都累加保存)
			$info['save_exp'] += ($animalCfg['add_exp'] * $scNum);
			$info['save_proficiency'] += ($animalCfg['add_proficiency'] * $scNum);
		} else if ($info['harvest_times'] && $info['food_val']) {
			$needSeconds = $animalCfg['food_val_reduce_need_seconds'];
			$intervalTime = $now - $info['last_reduce_food_val_time'];
			$needFoodVal = floor($intervalTime/$needSeconds);
			// 扣除饱食度超过剩余的,就只扣到0为止
			if ($needFoodVal >= $info['food_val']) {
				$needTime = $info['food_val'] * $needSeconds;
				$info['last_reduce_food_val_time'] += $needTime;
				$info['food_val'] = 0;
			} else {
				$needTime = $needFoodVal * $needSeconds;
				$info['last_reduce_food_val_time'] += $needTime;
				$info['food_val'] -= $needFoodVal;
			}
		} else {
//			var_dump($info['food_val']);
		}
//		var_dump($scNum);
//		echo $now;
//		echo "\n";
//		var_export($info);
//		exit;
		
		// 到达该时刻所扣的饱食度和最接近的扣饱食度时间
		if ($info['harvest_times']) {
			$_time = max($_time, $now);
			$intervalTime = $_time - $info['last_reduce_food_val_time'];
			$reduceFoodVal = floor($intervalTime/$animalCfg['food_val_reduce_need_seconds']);
			if ($reduceFoodVal > 0) {
				if ($info['food_val'] > $reduceFoodVal) {
					$needSeconds = $reduceFoodVal * $animalCfg['food_val_reduce_need_seconds'];
					$info['last_reduce_food_val_time'] += $needSeconds;
					$info['food_val'] -= $reduceFoodVal;
				} else {
					$needSeconds = $info['food_val'] * $animalCfg['food_val_reduce_need_seconds'];
					$info['last_reduce_food_val_time'] += $needSeconds;
					$info['food_val'] = 0;
				}
			}
		}
		
		$ret = $DB->update('raise', $info, 'id='.$info['id']);
		if ($ret !== false) {
			$ret = true;
		}
		
		
		$info['num'] = $outputItems;
		if (!$info['num']) {
			$info['num'] = null;
		}
		
		// 增加/解析字段信息
		$info['title']			= $animalCfg['title'];
		$info['product_id']		= $animalCfg['product_id'];
		$info['product_title']	= $animalCfg['product_title'];
		$info['skill_type']		= $animalCfg['skill_type'];
		$info['seed_id']		= $animalCfg['seed_id'];
		
		return $info;
	}
	
	/**
	 * 获取养殖建筑等级
	 * @param int $uid 用户ID
	 */
	public static function getLvl($uid)
	{
		global $DB;
		$sql = 'SELECT raise_lvl FROM user WHERE uid='.(int)$uid;
		return (int)$DB->getValue($sql);
	}
	
	/**
	 * 获取建筑信息
	 * @param int $uid
	 */
	public static function getInfo($uid)
	{
		global $DB, $L;
		$raiseLvl = (int)self::getLvl($uid);
		$raise    = C('build/raise');
		
		$result['val'] = $raiseLvl!==false ? true : false;
		if ($raiseLvl !== false) {
			$result['data'] = $raise[$raiseLvl];
			$result['data']['lvl'] = $raiseLvl;
			$result['data']['raise_max_mood_val'] = $G['raise_max_mood_val'];
		} else {
			$result['msg'] = $L['Failure'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('raise_get_info', $data);
		}
		return $result;
	}
	
	/**
	 * 获取所有栏位信息
	 * @param int $uid
	 * @param int $to_uid 获取他人的列表
	 */
	public static function getList($uid, $to_uid=null)
	{
		global $DB, $L, $max_plowland_num;
		
		$to_uid = (int)$to_uid;
		if ($to_uid) {
			$uid = $to_uid;
		}
		
		$sql   = 'SELECT * FROM raise WHERE uid='.(int)$uid;
		$tmpList = $DB->getList($sql);
		
		$list = array();
		$now  = time();
		
		$refreshTime = $now + 86400;
		foreach($tmpList as $record) {
			$record = self::handleSpaceInfo($record);
			$list[$record['pos']] = $record;
		}
		return array(
			'val'  => true,
			'data' => $list
//			'data' => array(
//				'list' => $list,
//				'refresh_time' => $refresh_time
//			)
		);
	}
	
	/**
	 * 养殖场扩建
	 * @param int $uid
	 */
	public static function extend($uid) 
	{
		global $DB, $L, $G;
		
		$sql = 'SELECT ticket,raise_extend_times FROM user WHERE uid='.$uid;
		$user = $DB->getValue($sql);
		
		$cfg = C('common/need_ticket');
		if ($user['raise_extend_times'] >= $cfg['raise_max_extend']) {
			return array(
				'val' => false,
				'msg' => $L['raise_extend_time_is_max']
			);
		}
		
		$needTicket = $cfg['raise_extend_need'][$user['raise_extend_times']+1];
		// 点券不足
		if ($needTicket > $user['ticket']) {
			return array(
				'val' => false,
				'msg' => $L['ticket_not_enough']
			);
		}
		
		$DB->beginTransaction();
		// 将扩建次数加1,且扣除对应的点券
		$sql = 'UPDATE user SET ticket=ticket-'.$needTicket.',raise_extend_times=raise_extend_times+1 WHERE uid='.$uid;
		$ret = $DB->exeSql($sql);
		if ($ret !== false) {
			$ret = true;
		}
		
		// 增加一个空位
		if ($ret) {
			$sql = 'SELECT MAX(pos) FROM raise WHERE uid='.$uid;
			$pos = $DB->getValue($sql);
			$data = array(
					'uid'			=> $uid,
					'pos'			=> $pos + 1,
					'status'		=> 0,
					'now_animal'	=> 0,
					'now_product'	=> 0,
					'raise_time'	=> 0,
					'growend_time'	=> 0,
					'end_sc_time'	=> 0,
					'num'			=> '',
					'food_val'		=> $G['default_food_val'],
					'mood_val'		=> $G['default_mood_val'],
			);
			$ret = $DB->insert('raise', $data);
		}
		
		$result['val'] = (bool)$ret;
		if ($ret) {
			// 处理成功,提交事务
			$DB->commit();
			$ret = self::getList($uid);
			$result['data'] = $ret['data'];
		} else {
			// 出错,回滚数据操作
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('raise_extend', $data);
		}
		
		return $result;
	}

	/**
	 * 升级
	 * @param int $uid
	 * @return boolean 
	 */
	public static function lvlUp($uid)
	{
		global $DB, $L, $G;
		$lvl = self::getLvl($uid);
		$nextLvl = $lvl+1;
		
		$raiseCfg = self::$cfg;
		
		// 是否已升级至满级
		end($raiseCfg);
		$maxLvl = key($raiseCfg);
		if ($nextLvl>$maxLvl) {
			return array(
				'val' => false,
				'msg' => $L['raise_is_max_lvl']
			);
		}
		
		$user = User::read($uid);
		// 需要金钱不足
		if ($user['coin'] < $raiseCfg[$lvl]['need_coin']) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}
		// 角色等级是否满足
		if ($user['lvl'] < $raiseCfg[$lvl]['need_mc_lvl']) {
			return array(
				'val' => false,
				'msg' => $L['mc_lvl_not_enough']
			);
		}
		
		$DB->beginTransaction();
		
		$data = array(
			'raise_lvl' => $nextLvl
		);
		$ret = $DB->update('user', $data, 'uid='.$uid);
		if ($ret !== false) {
			$ret = true;
		}
		
		// 扣除金钱
		if ($ret) {
			$sql = 'UPDATE user SET coin=coin-'.$raiseCfg[$lvl]['need_coin'].' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
			if ($ret !== false ) {
				$ret = true;
			}
		}
		
		
		$result['val'] = (bool)$ret;
		if ($ret) {
			// 增加新空位
			$data = array();
			
			$spacekNum     = $raiseCfg[$lvl]['space_num'];
			$nextSpaceNum = $raiseCfg[$nextLvl]['space_num'];
			
			// 添加上级之后pos到达下一次最大的数量的耕地
			$insert  = false;
			$sql = 'SELECT MAX(pos) FROM raise WHERE uid='.$uid;
			$pos = $DB->getValue($sql);
			$addPos = $nextSpaceNum - $spacekNum;
			for ($i=1; $i<=$addPos; $i++) {
				$pos += $i;
				// 更新数据
				$data = array(
					'uid'			=> $uid,
					'pos'			=> $pos,
					'status'		=> 0,
					'now_animal'	=> 0,
					'now_product'	=> 0,
					'raise_time'	=> 0,
					'growend_time'	=> 0,
					'end_sc_time'	=> 0,
					'num'			=> '',
					'food_val'		=> $G['default_food_val'],
					'mood_val'		=> $G['default_mood_val'],
				);
				$ret = $DB->insert('raise', $data);
				$result['val'] = (bool)$ret;
				if ($ret) {
					$insert = true;
				} else {
					$insert = false;
					$DB->rollBack();
					$result['msg'] = $L['Failure_Insert'];
					$data = var_export($DB->errors, true);
					// 记录错误日志
					Log::save('raise_lvl_up', $data);
					break;
				}
			}
			if ($insert) {
				$DB->commit();
				$result['data'] = array(
					'lvl' => $nextLvl,
					'pos' => $posList
				);
			} else {
				$DB->rollBack();
				$result['msg'] = $L['Failure_Insert'];
				$data = var_export($DB->errors, true);
				// 记录错误日志
				Log::save('raise_lvl_up', $data);
			}
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true).var_export($data,true);
			// 记录错误日志
			Log::save('raise_lvl_up', $data);
		}
		return $result;
	}
	
	/**
	 * 将幼仔放置在一个空栏中
	 * @param int $uid
	 * @param int $seedId 幼仔ID
	 * @param int $pos
	 */
	public static function lay($uid, $seedId, $pos)
	{
		global $DB, $L, $G;
		
		$seedId = (int)$seedId;
		$pos	= (int)$pos;
		$now = time();
		
		$sql = 'SELECT * FROM raise WHERE uid='.$uid.' AND pos='.$pos;
		$info = $DB->getValue($sql);
		
		//-- 对应位置是否已有动物
		if ($info['now_animal']) {
			return array(
				'val' => false,
				'msg' => $L['raise_space_had_animal']
			);
		}
		// 幼仔不存在
		$cfgList = C('item/seed_list');
		if (!isset($cfgList[$seedId])) {
			return array(
				'val' => false,
				'msg' => $L['no_such_young_animal']
			);
		}
		
		$animalId = $cfgList[$seedId];
		$cfgList = C('item/animal');
		$cfgInfo  = $cfgList[$animalId];
		
		if (is_null($cfgInfo)) {
			return array(
				'val' => false,
				'msg' => $L['no_such_young_animal']
			);
		}
		
		//-- 前置产品熟练度等级是否达到要求
		if ($cfgInfo['pre_animal']) {
			$sql = 'SELECT lvl FROM user_proficiency WHERE uid='.$uid.' AND item_id='.$cfgInfo['pre_animal'];
			$lvl = $DB->getValue($sql);
			if (!$lvl || $lvl < $G['pre_proficiency_lvl']) {
				return array(
					'val' => false,
					'msg' => $L['pre_animal_product_lvl_not_enough']
				);
			}
		}
		
		//-- 牧场等级是否达到要求
		$sql = 'SELECT lvl,coin FROM user WHERE uid='.$uid;
		$user = $DB->getValue($sql);
//		if ($user['lvl'] < $cfgInfo['need_mc_lvl']) {
//			return array(
//				'val' => false,
//				'msg' => $L['mc_lvl_is_not_enough']
//			);
//		}

		//-- 是否有足够的金钱
		if ($user['coin'] < $cfgInfo['seed_price']) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}
		
		
		//-- 是否有足够的幼仔
//		$sql = 'SELECT depot_id,num FROM depot WHERE uid=:uid and item_id=:item_id';
//		$param = array(
//			'uid' => $uid,
//			'item_id' => $seedId,
//		);
//		$itemInfo = $DB->getValue($sql, $param);
//		$num      = $itemInfo['num'];
//		if ($num <= 0) {
//			return array(
//				'val' => false,
//				'msg' => $L['seed_isnot_enough']
//			);
//		}
		
		//-- 技能等级是否达到要求
		
		$DB->beginTransaction();
		
		// 该作物成长需要时间
		$needTime = $cfgInfo['grow_need_time'];
		// 作物结束成长的时间点
		$endGrowupTime = $now + $needTime;
		
		// 更新栏位信息
		$data = array(
			'status'		=> 1,
			'now_animal'	=> $animalId,
			'raise_time'	=> $now,
			'growend_time'	=> $endGrowupTime,
			'end_sc_time'	=> 0,
			'harvest_times' => $cfgInfo['harvest_times'],
			'num'			=> '',
			'food_val'		=> $G['default_food_val'],
			'mood_val'		=> $G['default_mood_val'],
			'last_reduce_food_val_time'	=> $now,
		);
		$where = 'id='.$info['id'];
		$ret   = $DB->update('raise', $data, $where);
		
		//-- 扣除金钱
		if ($ret) {
			$sql = 'UPDATE user SET coin=coin-'.$cfgInfo['seed_price'].' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		$result['val'] = $ret;
		if ($ret) {
			// 处理成功,提交事务
			$DB->commit();
			$info['skill_type']			= $cfgInfo['skill_type'];
			$result['data']				= $data + $info;
			$result['data']['title']	= $cfgInfo['title'];
		} else {
			// 出错,回滚数据操作
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('raise_lay', $data);
		}
		
		return $result;
	}
//	
//	/**
//	 * 结束成长期,进入成熟期
//	 * @param int $uid 用户ID
//	 * @param int $pos 耕地的位置
//	 */
//	public static function endGrowUp($uid, $pos)
//	{
//		global $DB, $L;
//		
//		$now = time();
//		
//		if (self::$info) {
//			$info = self::$info;
//		} 
//		
//		if (!self::$info || self::$info['pos'] != $pos) {
//			$info = self::getSpaceInfo($uid, $pos, 0);
//		}
//		
//		if ($info['food_val'] == 0) {
//			return array(
//				'val' => false,
//				'msg' => $L['food_val_not_enough']
//			);
//		}
//		
//		// 当前栏位是空闲状态
//		if (empty($info['now_animal'])) {
//			return array(
//				'val' => false,
//				'msg' => $L['raise_space_is_idle']
//			);
//		}
//		
//		// 动物不在成长期
//		if ($info['growend_time'] == 0) {
//			return array(
//				'val' => false,
//				'msg' => $L['animal_hasnot_in_glowup'].' '.$pos
//			);
//		}
//
//		// 未到成熟期时间
//		if ($info['growend_time'] > $now) {
//			return array(
//				'val' => false,
//				'msg' => $L['animal_hasnot_end_glowup']
//			);
//		}
//		
//		
//		// 动物信息
//		$animalList       = C('item/animal');
//		$animalCfg		  = $animalList[$info['now_animal']];
//		$end_sc_need_time = $animalCfg['ripe_need_time'];
//		$end_sc_time      = $end_sc_need_time + $info['growend_time'];
//		
//		// 如果生成的成熟时间也是在过去时,则使动物生产出产品
//		if ($end_sc_time>0 && $end_sc_time<=$now) {
//			self::$info['growend_time'] = 0;
//			self::$info['end_sc_time'] = $end_sc_time;
//			$ret = self::endSc($uid, $pos);
//			if (!$ret['val']) {
//				return $ret;
//			}
//		}
//		
//		$data = array(
//			'status' => 2,
//			'now_product' => $animalCfg['product_id'],
//			'growend_time' => 0,
//			'end_sc_time' => $end_sc_time,
//		);
//		$where = 'id='.(int)$info['id'];
//		$ret   = $DB->update('raise', $data, $where);
//		$result['val'] = $ret;
//		if ($ret) {
//			$result['data'] = array(
//				'growend_time' => 0,
//				'end_sc_time' => $end_sc_time,
//				'end_sc_need_time' => $end_sc_need_time,
//				'status'	=> 2,
//			);
//		} else {
//			$result['msg'] = $L['Failure'];
//			$data = var_export($DB->errors, true);
//			// 记录错误日志
//			Log::save($typeName.'_end_growup', $data);
//		}
//		
//		return $result;
//		
//	}
	
	/**
	 * 收获产品
	 * @param int $uid 用户ID
	 * @param int $pos 栏位
	 */
	public static function getProduct($uid, $pos)
	{
		global $DB, $L, $G;
		
		$DB->beginTransaction();
		
		$info = self::getSpaceInfo($uid, $pos, 1);
		
		if (empty($info['num'])) {
			return array(
				'val' => false,
				'msg' => $L['raise_space_nothave_product']
			);
		}
		
		// 未到成熟时间
		if (empty($info['now_animal']) && ($info['end_sc_time']>time() || $info['end_sc_time']==0) ) {
			return array(
				'val' => false,
				'msg' => $L['animal_hasnot_end_glowup']
			);
		}
		
		$freeCapacity = Depot::getFreeCapacity($uid);
		// 仓库容量不足
		if ($freeCapacity == 0) {
			return array(
				'val' => false,
				'msg' => $L['not_enough_grid_in_depot']
			);
		}
		// 产品是否全部收获
		$allHarvest = ($freeCapacity >= array_sum($info['num']));
		
		$ret = false;
		
		$cfgList = C('item/animal');
		$cfgInfo = $cfgList[$info['now_animal']];
		//-- 收获物品进入仓库
		$qualityCfg = $G['quality_id'];
		$harvest = array();
		// 产品从小到大进行收获
		ksort($info['num']);
		foreach ($info['num'] as $quality => $num) {
			if ($num == 0) {
				unset($info['num'][$quality]);
				continue;
			}
			if ($freeCapacity == 0) {
				break;
			}
			if ($freeCapacity < $num) {
				$num = $freeCapacity;
				$info['num'][$quality] -= $num;
			} else {
				unset($info['num'][$quality]);
			};
			$data = array(
				'title'		=> $info['product_title'],
				'item_id'	=> $info['product_id'],
				'item_type'	=> $cfgInfo['product_item_type'],
				'num'		=> $num,
				'quality'	=> $quality,
				'lvl'		=> $cfgInfo['lvl']
			);
			$ret = Depot::in($uid, $data);
			if (!$ret['val']) {
				$DB->rollBack();
				return $ret;
			} else {
				$ret = true;
			}
			$harvest[$quality] = $num;
			
			// 当前收获后已经没有容量 了
			$freeCapacity -= $num;
			if ($freeCapacity == 0) {
				break;
			}
		}
		
	
		$DB->setTransactionState(false);
		//-- 生产获得熟练度
		if ($ret && $allHarvest) {
			$ret = User::addProficiency($uid, $info['save_proficiency'], $info['now_animal'], 3);
			if (!$ret['val']) {
				$DB->rollBack();
				return $ret;
			} else {
				$ret = true;
			}
		}
		//-- 收获获得经验
		if ($ret && $allHarvest) {
			$ret = User::addExp($uid, $info['save_exp']);
			if (!$ret['val']) {
				$DB->rollBack();
				return $ret;
			} else {
				$ret = true;
			}
		}
	
		
		// 是否可以获取惊喜宝箱
		if ($ret && $allHarvest && getRandResult($G['harvest_get_box_rate'])) {
			$item_id = 11006;
			$lvl = 0;
			$mailContent = sprintf($L['harvest_get_box'], $info['product_title']);
			$return = TreasureBox::get($uid, $item_id, $lvl, null, $mailContent);
			$ret = $return['val'];
			$inMail = $return['data']['in_mail'];
			$getTreasureBox = true;
		} else {
			$inMail = false;
			$getTreasureBox = false;
		}
		
		$DB->setTransactionState(true);


		//-- 修改栏位信息
		if ($ret) {
			// 全部收获清空空栏位信息
			if ($allHarvest) {
				$data = array(
					'growend_time'		=> 0,
					'num'				=> '',
					'save_exp'			=> 0,
					'save_proficiency'	=> 0,
				);
			} else {
				$data = array(
					'num'	=> json_encode($info['num']),
				);
			}
			$where = 'id='.(int)$info['id'];
			$ret   = $DB->update('raise', $data, $where);
			if ($ret !== false) {
				$ret = true;
			}
		}
		
		$result['val'] = $ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = self::getSpaceInfo($uid, $pos);
			$result['data']['get_treasure_box'] = $getTreasureBox;
			$result['data']['in_mail'] = $inMail;
			$result['data']['all_harvest'] = $allHarvest;
			if (!$allHarvest) {
				$result['data']['harvest'] = $harvest;
			}
		} else {
			if (isset($msg)) {
				$result['msg'] = $msg;
			} else {
				$result['msg'] = $L['Failure'];
			}
			$DB->rollBack();
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('raise_get_product', $data);
		}
		
		return $result;
	}
	
	/**
	 * 喂食
	 * @param int $uid
	 * @param int $pos
	 * @param int $depot_id
	 */
	public static function feeding($uid, $pos, $depot_id)
	{
		global $DB, $L, $G;

		$pos = (int)$pos;
		
		$info = self::getSpaceInfo($uid, $pos);
		if (isset($info['val']) && false === $info['val']) {
			return $info;
		}
		if (empty($info['status'])) {
			return array(
				'val' => false,
				'msg' => $L['raise_space_is_idle']
			);
		}
		
		$sql = 'SELECT uid,depot_id,item_id,num,quality FROM depot WHERE depot_id='.$depot_id;
		$itemInfo = $DB->getValue($sql);
		
		// 牧草不是自己的
		if ($itemInfo['uid'] != $uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		// 没有牧草
		if (!$itemInfo || $itemInfo['num'] <= 0) {
			return array(
				'val' => false,
				'msg' => $L['pasture_is_not_enough']
			);
		}
		
		$foodVal = $G['feeding_quality_add_food_val'][$itemInfo['quality']];
		// 最少增加的饱食度加上当前的也会超出上限时给出提示
		if (($foodVal[0] + $info['food_val']) > $G['raise_max_food_val']) {
			return array(
				'val' => false,
				'msg' => $L['raise_food_val_may_max']
			);
		}
		
		/* 喂食之前获取栏位信息时已调整栏位数据(即已是当前未喂食的状态) */
//		var_export($info);
//		echo "\n";
		
		// 增加心情,饱食度
		$now = $_SERVER['REQUEST_TIME'];
		$moodVal = $info['mood_val'] + $G['feeding_quality_add_mood_val'][$itemInfo['quality']];
		// 增加的饱食度
		$addFoodVal = rand($foodVal[0], $foodVal[1]);
		$foodVal = $info['food_val'] + $addFoodVal;
		
		// 修正饱食度,使值不会超过最大值
		$moodVal > $G['raise_max_mood_val'] && $moodVal = $G['raise_max_mood_val'];
		$foodVal > $G['raise_max_food_val'] && $foodVal = $G['raise_max_food_val'];
		
		if ($info['food_val'] == 0) {
			$endScTime = $now + ($info['end_sc_time'] - $info['last_reduce_food_val_time']);
			$sql = 'UPDATE raise set mood_val='.$moodVal
				.', food_val='.$foodVal.',last_reduce_food_val_time='.$now
				.', end_sc_time='.$endScTime
				.'  WHERE id='.$info['id'];
		} else {
			$sql = 'UPDATE raise set mood_val='.$moodVal.', food_val='.$foodVal
				.'  WHERE id='.$info['id'];
		}
		
		
		$DB->beginTransaction();
		
		$ret = $DB->exeSql($sql);
		
		
		// 扣除饲料(牧草)
		if ($ret) {
			$sql = 'UPDATE depot SET num=num-1 WHERE depot_id='.$itemInfo['depot_id'];
			$ret = $DB->exeSql($sql);
			if ($ret !== false) {
				$ret = true;
			}
		}
		
		$result['val'] = $ret;
		if ($ret) {
			$result['data'] = self::getSpaceInfo($uid, $pos);
			$DB->commit();
		} else {
			$result['msg'] = $L['Failure'];
			$DB->rollBack();
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('raise_feeding', $data);
		}
		
		return $result;
	}
	
	/**
	 * 获取种子列表
	 * @param $uid
	 */
	public static function getSeedList($uid)
	{
		return Town::getAnimalList($uid);
	}
	
	/**
	 * 清理
	 * @param int $uid 用户ID
	 * @param int $pos 位置
	 */
	public static function eradicate($uid, $pos)
	{
		global $DB, $L, $G;
		
		$DB->beginTransaction();
		
		$data = array(
			'status'		=> 0,
			'now_animal'	=> 0,
			'now_product'	=> 0,
			'raise_time'	=> 0,
			'growend_time'	=> 0,
			'end_sc_time'	=> 0,
			'num'			=> '',
			'save_exp'		=> 0,
			'save_proficiency'	=> 0,
			'food_val'		=> 0,
			'mood_val'		=> 0,
			'harvest_times'	=> 0,
			'last_reduce_food_val_time'	=> 0,
		);
		$pos = (int)$pos;
		$ret = $DB->update('raise', $data, 'uid='.$uid.' and pos='.$pos);
		$ret!==false && $ret = true;
		
		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = self::getSpaceInfo($uid, $pos);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('raise_harvest', $data);
		}
		return $result;
	}
	
	/********************************************
	 * 互动部分
	 ********************************************/
	
	/**
	 * 偷窃
	 * @param int $uid
	 * @param int $to_uid
	 * @param int $pos
	 */
	public static function steal($uid, $to_uid, $pos) 
	{
		global $DB, $L, $G;
		
		if ($uid == $to_uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$userInfo = User::read($uid, 'lvl,seriate_steal_times,last_steal_time,energy_point,in_prison');
		
		// 能量点不够
		if (!$userInfo['energy_point']) {
			return array(
				'val' => false,
				'msg' => $L['energy_point_not_enough']
			);
		}
		
		// 判断是否好友
		if (!Friend::isFriend($uid, $to_uid)) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$posInfo = self::getSpaceInfo($to_uid, $pos);
		// 不在生产周期内,不能偷窃
		if ($posInfo['status'] != 2) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		// 已经被偷过了
		if ($posInfo['is_stolen']) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$now = time();
		
		$toUserInfo = User::read($uid, 'lvl,seriate_steal_times,last_steal_time');
		if ($userInfo['in_prison']) {
			$sql = 'SELECT * FROM prison WHERE uid='.$uid;
			$prisonInfo = $DB->getValue($sql);
			if (!$prisonInfo['can_interactive']) {
				return array(
					'val' => false,
					'msg' => $L['cannot_steal_in_prison']
				);
			}
		}
		
		// 载入互动操作配置
		C('common/interactive');
		
		// 上次偷窃时间到现在超过24小时,连续偷窃次数清零
		if ($userInfo['last_steal_time'] < ($now-86400)) {
			$stealTimes = 0;
			$seriateStealParam = $G['seriate_steal_param'][0];
		} else {
			$stealTimes = $userInfo['seriate_steal_times'] + 1;
			if (isset($G['seriate_steal_param'][$userInfo['seriate_steal_times']])) {
				$seriateStealParam = $G['seriate_steal_param'][$userInfo['seriate_steal_times']];
			} else {
				$seriateStealParam = 0;
			}
		}
		
		if ($seriateStealParam) {
			$differenceLvl = abs($userInfo['lvl'] - $toUserInfo['lvl']);
			$cfgList = C('item/animal');
			$cfg = $cfgList[$posInfo['now_animal']];
			$successRate = $G['base_steal_success_rate'][$cfg['lvl']]
							* $G['difference_lvl_steal_param'][$differenceLvl]
							* $G['seriate_steal_param'][$stealTimes];
			$success = getRandResult($successRate);
		} else {// 参数为0,肯定失败
			$success = false;
		}
		
		$DB->beginTransaction();
		$DB->setTransactionState(false);
		
		$result['data'] = array(
			'success' => $success
		);
		
		if ($success) {
			$addition = 0;
			foreach ($posInfo['num'] as $quality=>$num) {
				$addition += ($num * $G['steal_coin_prize_param'][$quality]);
			}
			// 获得金钱奖励
			$getCoin = $G['steal_coin_prize_base_value'] + $addition;
			$sql = 'UPDATE user SET coin=coin+'.$getCoin.',energy_point=energy_point-1,
					seriate_steal_times='.$stealTimes.',last_steal_time='.$now.' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
			if ($ret) {
				$result['data']['get_coin'] = $getCoin;
			}
			
			if ($ret) {
				$sql = 'UPDATE farm SET is_stolen=1 WHERE fid='.$posInfo['fid'];
				$ret = $DB->exeSql($sql);
			}
		} else {
			// 关进监狱
			$ret = Prison::detain($uid);
			
			// 扣除能量点
			if ($ret) {
				$sql = 'UPDATE user SET energy_point=energy_point-1,
						seriate_steal_times=0,last_steal_time='.$now.' WHERE uid='.$uid;
				$ret = $DB->exeSql($sql);
			}
		}
		
		$DB->setTransactionState(true);

		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('raise_steal', $data);
		}
		return $result;
	}
	
	/**
	 * 清洁
	 * @param $uid
	 * @param $to_uid 被维修的采集场主人用户ID
	 * @param $pos 采集场位置
	 */
	public static function clean($uid, $to_uid, $pos) 
	{
		global $DB, $L, $G;
		
		$userInfo = User::read($uid, 'lvl,seriate_steal_times,last_steal_time,energy_point');
		// 能量点不够
		if (!$userInfo['energy_point']) {
			return array(
				'val' => false,
				'msg' => $L['energy_point_not_enough']
			);
		}
		
		// 判断是否好友
		if (!Friend::isFriend($uid, $to_uid)) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$posInfo = self::getSpaceInfo($to_uid, $pos);
		// 只能生产状态可以清洁
		if ($posInfo['status'] != 2) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		// 已经清洁过了
		if ($posInfo['is_cleaned']) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		// 饱食度不足
		if (!$posInfo['food_val']) {
			return array(
				'val' => false,
				'msg' => $L['food_val_not_enough_to_clean']
			);
		}
		
		$now = time();
		
		$DB->beginTransaction();
		$DB->setTransactionState(false);
		
		// 载入互动操作配置
		C('common/interactive');
		
		$cfgList = C('item/animal');
		$cfg = $cfgList[$posInfo['now_animal']];
		// 减少时间
		$reduceTime = round($cfg['ripe_need_time'] * $G['clean_reduce_time']);
		$sql = 'UPDATE raise SET is_maintained=1,end_sc_time=end_sc_time-'.$reduceTime.' WHERE fid='.$posInfo['fid'];
		$ret = $DB->exeSql($sql);
		
		// 扣除能量点
		if ($ret) {
			$sql = 'UPDATE user SET energy_point=energy_point-1 WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		// 增加经验
		if ($ret) {
			$ret = User::addExp($uid, $G['maintain_get_exp']);
		}
		
		$DB->setTransactionState(true);

		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
				'info'		=> self::getSpaceInfo($to_uid, $pos),
				'get_exp'	=> $G['weed_get_exp']
			);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_weed', $data);
		}
		return $result;
	}
}





